<script setup >
import { ref, onMounted, reactive, getCurrentInstance, nextTick,computed } from "vue";
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import {
    Document,
    Menu as IconMenu,
    Location,
    Setting,
    UploadFilled,
    Delete, Download, Plus, ZoomIn
} from '@element-plus/icons-vue'
import { errorMessages } from "vue/compiler-sfc";

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// const imgDialogVisible = ref(false);
const disabled = ref(false)
const { proxy } = getCurrentInstance()
const router = useRouter()
const provinces = ref([
    {
        name: '北京市',
        cities: ['北京市']
    },
    {
        name: '广东省',
        cities: ['广州市', '深圳市', '珠海市', '汕头市', '韶关市']
    },
    {
        name: '江苏省',
        cities: ['南京市', '苏州市', '无锡市', '常州市', '镇江市']
    },
    {
        name: '浙江省',
        cities: ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市']
    },
    {
        name: '山东省',
        cities: ['济南市', '青岛市', '烟台市', '潍坊市', '济宁市']
    },
    {
        name: '河南省',
        cities: ['郑州市', '洛阳市', '南阳市', '新乡市', '许昌市']
    },
    {
        name: '四川省',
        cities: ['成都市', '绵阳市', '德阳市', '自贡市', '泸州市']
    },
    {
        name: '河北省',
        cities: ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市']
    },
    {
        name: '湖南省',
        cities: ['长沙市', '株洲市', '湘潭市', '岳阳市', '常德市']
    },
    {
        name: '安徽省',
        cities: ['合肥市', '芜湖市', '马鞍山市', '淮南市', '淮北市']
    }
]);
const options = [
    {
        value: '广东省',
        label: '广东省',
        children: [
            {
                value: '广州市',
                label: '广州市',
                children: [
                    { value: '越秀区', label: '越秀区' },
                    { value: '天河区', label: '天河区' },
                    { value: '白云区', label: '白云区' },
                    { value: '番禺区', label: '番禺区' },
                ],
            },
            {
                value: '深圳市',
                label: '深圳市',
                children: [
                    { value: '罗湖区', label: '罗湖区' },
                    { value: '福田区', label: '福田区' },
                    { value: '南山区', label: '南山区' },
                    { value: '宝安区', label: '宝安区' },
                ],
            },
            {
                value: '珠海市',
                label: '珠海市',
                children: [
                    { value: '香洲区', label: '香洲区' },
                    { value: '斗门区', label: '斗门区' },
                ],
            },
        ],
    },
    {
        value: '北京市',
        label: '北京市',
        children: [
            {
                value: '东城区',
                label: '东城区',
            },
            {
                value: '西城区',
                label: '西城区',
            },
            {
                value: '朝阳区',
                label: '朝阳区',
            },
            {
                value: '海淀区',
                label: '海淀区',
            },
        ],
    },
    {
        value: '上海市',
        label: '上海市',
        children: [
            {
                value: '黄浦区',
                label: '黄浦区',
            },
            {
                value: '徐汇区',
                label: '徐汇区',
            },
            {
                value: '长宁区',
                label: '长宁区',
            },
            {
                value: '静安区',
                label: '静安区',
            },
        ],
    },
    {
        value: '浙江省',
        label: '浙江省',
        children: [
            {
                value: '杭州市',
                label: '杭州市',
                children: [
                    { value: '玄武区', label: '玄武区' },
                    { value: '秦淮区', label: '秦淮区' },
                ],
            },
            {
                value: '宁波市',
                label: '宁波市',
                children: [
                    { value: '姑苏区', label: '姑苏区' },
                    { value: '吴江区', label: '吴江区' },
                ],
            },
        ],
    },
    {
        value: '河南省',
        label: '河南省',
        children: [
            {
                value: '郑州市',
                label: '郑州市',
                children: [
                    { value: '玄武区', label: '玄武区' },
                    { value: '秦淮区', label: '秦淮区' },
                ],
            },
            {
                value: '洛阳市',
                label: '洛阳市',
                children: [
                    { value: '姑苏区', label: '姑苏区' },
                    { value: '吴江区', label: '吴江区' },
                ],
            },
        ],
    },
    {
        value: '江苏省',
        label: '江苏省',
        children: [
            {
                value: '南京市',
                label: '南京市',
                children: [
                    { value: '玄武区', label: '玄武区' },
                    { value: '秦淮区', label: '秦淮区' },
                ],
            },
            {
                value: '苏州市',
                label: '苏州市',
                children: [
                    { value: '姑苏区', label: '姑苏区' },
                    { value: '吴江区', label: '吴江区' },
                ],
            },
        ],
    },
    // 继续添加其他省市的结构...
];
const base64Data = ref('')
const dialogFormVisible = ref(false)
const dialogButtonVisible = ref(false);
const buttonType = ref('primary');
let cards = ref([]);
const filteredCards = ref([]);
let imagesURL = ref([]);
const loading = ref(true);
const filename = 'download.png';
let buttonText = ref('编辑模式');
let placeText = ref('请选择地址')
const action = ref('add')
const upload = ref(null); 
const form = ref({
    id:'',
    aname: '',
    address: '',
    index: null,
    img64Data:''
});
const editMode = async() =>  {
    // 切换按钮类型和文字
    
    if (buttonType.value === 'primary') {
        buttonType.value = 'danger';
        buttonText.value = '退出编辑';
        dialogButtonVisible.value = true;
        dialogButtonVisible.value = true
    } else {
        buttonType.value = 'primary';
        buttonText.value = '编辑模式';
        dialogButtonVisible.value = false;
    }
    await nextTick();
};
const allMenuClick = () => {
    getNCardData()
}
const getImageUrl = (user) => {
    return new URL(`../assets/images/${user}.png`, import.meta.url).href
} ;
const getNCardData = async () => {
    try {
        const data = await proxy.$api.getNCardData(); 
        cards.value = data.cards;
        filteredCards.value = cards.value;
    } catch (error) {
        console.error('Error fetching NCard data:', error);
    }
}

const handleEdit = (id,aname, address,img64Data,index) => {
    // console.log('编辑:', id,aname, address,index);
    // 在这里处理编辑逻辑，比如打开对话框、填充表单等
    dialogFormVisible.value = true;  
    action.value = 'edit';
    placeText.value = address;
    // form.value.id = id;  
    // form.value.aname = aname;
    // form.value.address = address; 
    console.log(img64Data);
       
    dialogImageUrl.value = img64Data;
    console.log("设置的 dialogImageUrl:", dialogImageUrl.value);
    form.value = { id, aname, address,img64Data ,index };
    // console.log(address);
    dialogFormVisible.value = true;
    
};
const addressString = computed(() => {
    return addressArray.value.join(' '); 
});
// const handleRemove = function (files) {
//     upload.value.clearFiles();
//     // const file = files[0];
//     // file.uid = getFileId();
//     // upload.value.handleStart(file);
// };
const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url;
    console.log("1:",file.url);
    dialogVisible.value = true;
};

const handleDownload = (file) => {
    console.log(file);
    const downloadLink = document.createElement('a');
    downloadLink.href = file.url; 
    downloadLink.download = file.name;
    downloadLink.click();
};
const handleExceed = function (files) {
    ElMessage.error('只允许上传一张图片')
};
const handleRemove = function (files) {
    upload.value.clearFiles();
};
//111111111111111111111111111111111111111111111111111111111111111111111111111111111111
//img
// function getBase64(file) {
//     return new Promise((resolve, reject) => {
//         let reader = new FileReader();

//         // 读取文件为 Data URL (Base64)
//         reader.readAsDataURL(file);

//         reader.onload = () => {
//             // 成功读取文件
//             resolve(reader.result); // 返回 Base64 字符串
//         };

//         reader.onerror = (error) => {
//             // 读取文件出错
//             reject(error);
//         };
//     });
// }
const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
};
function base64ToFile(base64, filename) {
    const arr = base64.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new File([u8arr], filename, { type: mime });
}

const beforeUpload = (file) => {
    console.log('准备上传的文件:', file); // 确保文件对象存在
    return true; // 允许上传
};
// 
const handleUploadChange = (file) => {
    console.log("handleUploadChange");
    console.log(file); // 确保文件对象存在

    // 确保使用 file.raw 来获取原始文件对象
    const rawFile = file.raw || file; // 根据实际情况获取有效的文件对象

    getBase64(rawFile).then(base64String => {
        base64Data.value = base64String;
        // console.log('Base64 Data:', base64Data.value);
        form.value.img64Data = base64String
        // console.log('img64Data Data:', base64Data.value);
        // const file22 = base64ToFile(base64Data.value, filename);
        // console.log("重新转化为file", file22);

        // 设置预览图像的 URL
        // console.log("dialogImageUrl.value",base64Data.value);
        
        dialogImageUrl.value = base64Data.value; // 显示图片预览
    }).catch(error => {
        console.error('Error converting to Base64:', error);
    });
};

const saveImageToServer = (base64Data) => {
    console.log("111111111111111111111");
    
    // 这里是发送 Base64 数据到后端的逻辑
    axios.post('https://your-server.com/api/upload', {
        image: base64Data
    })
        .then(response => {
            console.log('上传成功:', response.data);
        })
        .catch(error => {
            console.error('上传失败:', error);
        });
};

const handleUploadSuccess = (response, file) => {
    console.log("success");
    
    // 上传成功处理逻辑
};

const save = (index) => {
    let res = null
    console.log(form.value.address);
    if (Array.isArray(form.value.address)) {
        form.value.address = form.value.address.join(' '); // 转换为字符串
    }
    console.log("form",form);
    
    if (action.value == "add") {
        res = proxy.$api.addNCardData(form.value);
        if (res) {
            getNCardData();
            console.log(res);
            
            res.value = null
        }
    } else if (action.value == "edit") {
        if (index >= 0) {
            res = proxy.$api.editNCardData(form.value);
            console.log(res);
            if(res){
                getNCardData();
                res.value = null
            }
        } else {
            console.log("error");
            //生成新卡片
            // cards.value.push({
            //     id: Date.now(),
            //     aname: form.value.aname,
            //     address: form.value.address
            // });
        }
    }
    getNCardData();
    dialogFormVisible.value = false;
};
const handleDelete = (id,index) =>{
    console.log(id,index);
    ElMessageBox.confirm("确定删除这条数据吗", {
        cancelButtonText: '取消',
        confirmButtonText: '确定'
    }).then(async () => {
        // 用户点击了“确定”  
        await proxy.$api.deleteNCardData({ id: id });
        ElMessage({
            showClose: true,
            message: "删除成功",
            type: 'success'
        });
        getNCardData();
    }).catch(() => {
        // 用户点击了“取消”  
        ElMessage({
            showClose: true,
            message: "已取消删除",
            type: 'info'
        });
    });
    
}
const handleAdd = () => {
    form.value.aname = '';
    form.value.address = '';
    form.value.img64Data = ' ';
    placeText.value = '请选择地址'
    dialogFormVisible.value = true;
    action.value = 'add';

}
const handleMenuClick = (cityName) => {

    filteredCards.value = cards.value.filter(card => {
        const address = card.address;
        return address.includes(cityName);
    });

};
const dialogClosed = () => {
    console.log("已经关闭");
    // dialogImageUrl.value = ''; // 清空预览图像
    upload.value.clearFiles();
    
}
onMounted(()=>{
    getNCardData();
})

</script>

<template>
    <div class="main">

        <div class="menu-container">
            <el-affix :offset="65" class="menu-affix" style="height: 100%;">
                <el-scrollbar>
                    <el-menu default-active=" 2" class="el-menu-vertical-demo"
                        style="height: 100vh;margin-bottom: 10px;">
                        <template #title>
                            <el-icon>
                                <location />
                            </el-icon>
                            <span>城市</span>
                        </template>
                        <el-menu-item index="0" @click="allMenuClick()">
                            <el-icon><icon-menu /></el-icon>
                            <span>全国</span>
                        </el-menu-item>
                        <el-sub-menu v-for=" (province, index) in provinces" :key="index" :index="'1-' + index">

                            <template #title>
                                <span>{{ province.name }}</span>
                            </template>
                            <el-menu-item v-for="(city, cityIndex) in province.cities" :key="cityIndex"
                                :index="'1-' + index + '-' + cityIndex" @click="handleMenuClick(city)">
                                {{ city }}
                            </el-menu-item>
                        </el-sub-menu>
                    </el-menu>
                </el-scrollbar>

            </el-affix>

        </div>
        <div class="right-container">
            <div class="header">
                <div class="edit">
                    <el-button class="addbutton" type="primary" @click="handleAdd"
                        v-if="dialogButtonVisible">添加地址</el-button>
                    <el-affix :offset="65" class="edit-container">
                        <el-button class="editMode" :type="buttonType" @click="editMode" plain>{{ buttonText
                            }}</el-button>
                    </el-affix>
                </div>
            </div>

            <div class="card-container">
                <!-- <el-scrollbar> -->
                <el-card shadow="hover" v-for="(card,index) in filteredCards" :key="card.id" class="card-item">
                    <h3>{{ card.aname }}</h3>
                    <p>{{ card.address }}</p>
                    <!-- <img :src=" getImageUrl('food')" class="card-img"> -->
                    <img :src="card.img64Data || getImageUrl('food')" class="card-img">
                    <el-button v-if="dialogButtonVisible"
                        @click="handleEdit(card.id, card.aname, card.address, card.img64Data,index)" class="editButton"
                        type="primary" icon="Edit" circle />
                    <el-button v-if="dialogButtonVisible" @click="handleDelete(card.id,index)" class="deleteButton"
                        type="danger" icon="Delete" circle />
                </el-card>
                <!-- </el-scrollbar> -->
            </div>
        </div>

    </div>
    <!-- <el-col :span="7" style="margin-top: 20px"> -->
    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="信息" width="40%" @close="dialogClosed">
        <el-form class="form-container" :model="form" label-width="100px" style="padding-right:30px ">
            <el-form-item label="名字">
                <el-input v-model="form.aname" autocomplete="off" />
            </el-form-item>
            <!-- <el-form-item label="地址">
                <el-input v-model="form.address" autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="地址">
                <el-cascader v-model="form.address" :placeholder="placeText" style=" width: 450px;" :options="options"
                    clearable separator=" " />
            </el-form-item>
            <el-form-item label="图片">

                <el-upload ref="upload" action="" list-type="picture-card" :auto-upload="false"
                    @change="handleUploadChange" :limit="1" :on-exceed="handleExceed">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>

                            <!-- <img class="el-upload-list__item-thumbnail" :src="file.url || getImageUrl('food')" alt="" /> -->

                            <img class="el-upload-list__item-thumbnail" :src=" dialogImageUrl" alt="" />
                            <span class="el-upload-list__item-actions">
                                <!-- <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <el-icon><zoom-in /></el-icon>
                                </span> -->
                                <span v-if="!disabled" class="el-upload-list__item-delete"
                                    @click="handleDownload(file)">
                                    <el-icon>
                                        <Download />
                                    </el-icon>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>
                <el-form-item>
                    <p class="el-upload__tip " style="red">
                        只能上传一张照片
                    </p>

                </el-form-item>
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="save(form.index)">保存</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<style lang="less" scoped>
.body{
    overflow: auto;
    height: 100%-120px;
}
.main{
    // padding-top: 60px;
    // top: 60px;
    height: calc(100%-60px)!important;
    position: relative;
}
.header{
    height: 40px;
}
.edit{
    display: flex;
    justify-content:right;

    
}
.edit el-affix{
    position: absolute;
    // display: inline-block;
}
.editMode{
    margin-right: 20px;
}
.addbutton{
    margin-top: 65px;
    margin-right: 10px;
    // margin-top: 5px;
}
.el-upload__tip{
    color: red;
}
.nCard{
    height: 200px;
    width: 350px;
    margin-bottom: 20px;
}
.preview_Image{
    display: block; 
    max-width: 100%; 
    max-height: 100%; 
    margin: auto;
}
// .el-upload-list__item-thumbnail{
//     margin-right: 20px;
// }
.menu-container{
    position: absolute;
    height: 100vh;
    
}
.menu-container .menu-affix{
    position: relative;
    width: 170px;
    height: 100vh;
    background-color: #fff;
}
.el-menu-vertical-demo{
    height: 100vh;
}
.el-menu-vertical-demo .el-menu-item.is-active {
    background-color: rgb(88, 170, 252);
    color: #fff;
}

.card-container {
    margin-top: 60px;
    overflow-y: auto;
    margin-left: 190px;
    height: calc(100vh-60px);
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
}

.card-item {
    flex: 0 1 calc(33.333% - 16px);
    box-sizing: border-box;
    position: relative;
    height: 200px;
}
// .card-item {
//     height: 200px;
//     margin-bottom: 20px;
// }
.card-item h3{
    font-size: 20px;
    margin-bottom: 10px;
    position: absolute;
    top: 10%;
}
.card-item p{
    color: darkgray;
    position: absolute;
    top: 25%;
    max-width: 50%;
    line-height: 20px;
    
}
.card-item .editButton{
    position: absolute;
    top: 150px;
    
}
.card-item .deleteButton {
    position: absolute;
    top: 150px;
    left: 60px;
}
.card-img {
    position: absolute;
    width: 36%;
    top: 50%;
    transform: translateY(-50%);
    border-radius: 10px;
    right: 15px;
}

// @media (max-width: 768px) {
//     .card-item {
//         flex: 1 1 calc(50% - 16px);
//     }
// }

// @media (max-width: 480px) {
//     .card-item {
//         flex: 1 1 100%;
//     }
// }

.form-container .el-form-item {
    width: 85% !important;
}

.form-container el-input,
.form-container el-cascader,
.form-container el-cascader el-tooltip__trigger el-tooltip__trigger{
    width: 100% !important;
}
</style>